<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/music'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm: any = ref({
  musicUrl: '',
  soundOnIcon: '',
  soundTurnOffIcon: '',
  backgroundPic: '',
  description: '',
  enable: true,
})

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  if (url) {
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData() {
  // console.log(ruleForm.value)
  // ruleForm.value.backgroundPic = ruleForm.value.backgroundPic.join(',')
  if (id) {
    // 编辑
    ruleForm.value.id = id
    PutModifyData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'musicIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`编辑失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`编辑失败。${errorStr}`)
        }
      }
    })
  }
  else {
    // 添加
    PostCreateData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyMusic()
        router.push({ name: 'musicIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`添加失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`添加失败。${errorStr}`)
        }
      }
    })
  }
}

watch(ruleForm, (newValue) => {
  detailData.RememberMusic(newValue)
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        // ruleForm.value.backgroundPic = res.data.backgroundPic.split(',')
      }
    })
  }
  else {
    ruleForm.value = detailData.GetMusicData()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="是否启用">
              <el-switch
                v-model="ruleForm.enable"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="音乐地址">
              <!-- <ImageUpload
                :size="1" :url="ruleForm.musicUrl" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'musicUrl')"
              /> -->
              <FileUpload :url="ruleForm.musicUrl" :ext="['mp3']" :size="50" :max="1" @on-success="(fileUrl: string) => handleUploadSuccess(fileUrl, 'musicUrl')" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享语">
              <el-input v-model="ruleForm.description" style="width: 300px;" placeholder="请输入分享语" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="开启声音图标">
              <ImageUpload
                :size="1" :url="ruleForm.soundOnIcon" @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'soundOnIcon')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="关闭声音图标">
              <ImageUpload
                :size="1" :url="ruleForm.soundTurnOffIcon" @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'soundTurnOffIcon')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="背景图">
              <ImagesUpload
                :height="400" :width="200" :size="1" :max="10"
                :url="ruleForm.backgroundPic" :ext="['jpg', 'png']"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

  <style lang="scss" scoped>
  :deep(.el-date-editor) {
    width: 100%;
  }

  .tag {
    max-width: 300px;
    color: red;
  }
  </style>
